from room import Room


class Map(object):
    """
        Unfortunately for now, map will have 2 purposes... build maps [ join rooms, define room ]
        and managing interactions with the rooms
    """
    
    def __init__(self, title, rooms = None):
        self.title = title
        self.rooms = rooms or {}
        
    
    def create(self, **kw ):
        temp = Room(**kw)
        self[temp] = temp
        return self[temp.id]
        
    def join(self, exit, enter,  parent, target):
        
        if parent.id not in self:
            raise Exception("Parent is not in the map currently!")
            
        if target.id not in self:
            raise Exception("Parent is not in the map currently!")
        
        parent.exits[exit] = target.id        
        target.exits[enter] = parent.id
        
        if parent.id == target.id:
            raise Warning("Parent & Target are the same room, was this intended?")
                
    def list(self):
        """
          Not perfect but I need something for displaying data
        """
        return [(k,v) for k,v in self.rooms.items()]
    
    def __setitem__(self, key, item):
        if isinstance(key, Room):
            self.rooms[item.id] = item
        else:
            raise ValueError("Key must be an instance of room for map()[key] = value")
    
    def __getitem__(self, key):
        if isinstance(key, Room):
            key = key.id
        return self.rooms.get(key, None)
        
    def __contains__(self, item):        
        id = item.id if isinstance(item, Room) else item            
        return self.rooms.has_key(id)
        
    def __setstate__(self, state):
        self.title = state["title"]
        self.rooms = state.get("rooms",None) or {}
    def __getstate(self):
        return {"title": self.title, "rooms": self.rooms}
        
   
    